
/*
 * sndpipe: A UNIX pipes-based audio stream processor toolkit.
 * Copyright (C) 2011  Bradley Worley
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to:
 *
 *   Free Software Foundation, Inc.
 *   51 Franklin Street, Fifth Floor
 *   Boston, MA  02110-1301, USA.
 */

/* include the sndpipe header. */
#include "sndpipe.h"

void func_cap (void) {
  struct pipes *pi, *po;
  struct hardware *hw;
  SF_INFO sfi;
  unsigned long c, hc, i, rate, channels, frames;
  double **buf, **hwbuf;

  channels = opts_get_int (OPTS_S_CHANNELS);
  rate = opts_get_int (OPTS_S_RATE);

  memset (&sfi, 0, sizeof (sfi));

  pi = pipes_open_input ();
  if (pi) {
    sfi.samplerate = pi->sfi.samplerate;
    sfi.channels = pi->sfi.channels + channels;
    sfi.format = pi->sfi.format;
  }
  else {
    sfi.samplerate = rate;
    sfi.channels = channels;
    sfi.format = pipes_get_format ();
  }

  ASSERT (sfi.format);

  frames = 0;
  po = pipes_open_output (sfi);
  buf = pipes_buf_alloc (po, &frames);

  hw = hw_open_input (rate);
  ASSERT (hw);

  hwbuf = hw_buf_alloc (hw, &frames);

  do {
    if (pi)
      ASSERT (pipes_read (pi, &buf, frames) == SP_OK);

    ASSERT (hw_read (hw, &hwbuf, frames) == SP_OK);

    hc = 0;
    for (c = pi ? pi->sfi.channels : 0; c < po->sfi.channels; c++) {
      for (i = 0; i < frames; i++) {
        buf[c][i] = hwbuf[hc][i];
      }

      hc++;
    }
  } while (pipes_write (po, buf, frames) == SP_OK);

  hw_buf_free (hw, frames, hwbuf);

  pipes_buf_free (po, frames, buf);

  hw_close (hw);

  ASSERT (pipes_close (pi) == SP_OK);
  ASSERT (pipes_close (po) == SP_OK);
}

